//
//  SEGOrderDetailCell.m
//  Uhomebk
//
//  Created by mac on 2017/7/7.
//  Copyright © 2017年 com.segi. All rights reserved.
//

#import "SEGOrderDetailCell.h"
#import "ControlTemplateViewRecordController.h"
//#import "PhotoBroswerVC.h" //照片
#define ORDER_DETAIL_CONTENT_FONT kFont_15

@interface SEGOrderDetailCell ()

@property (weak, nonatomic) IBOutlet UIButton *openButton;
@property (nonatomic, strong) UIButton *foldButton;

@end

@implementation SEGOrderDetailCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.titleBgView.backgroundColor = kColor_W;
    self.detailBgView.backgroundColor = kColor_W;
    [self.openButton setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"icon_list_popup_black")] forState:UIControlStateNormal];
}

-(void)clearContentView
{
    for (UIView *view in self.contentView.subviews) {
                [view removeFromSuperview];
            }
}

//-(void)paddingDataWith:(id)data
//{
//    [self clearContentView];
//
//    if (templateVC) {
//        templateVC = nil;
//    }
//    templateVC = [[ControlTemplateViewController alloc] init];
//    templateVC.mastVC = self.controller;
//    templateVC.isCloseGroup = YES;//关闭分组
//    templateVC.isCloseLine = YES;//关闭分割线
//    NSArray *dataArr = data;
//
//   __block UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.bounds), 0)];
//    scrollView.showsHorizontalScrollIndicator = NO;
//    scrollView.showsVerticalScrollIndicator = NO;
//    scrollView.scrollEnabled = NO;
//    [self.contentView addSubview:scrollView];
//
//    [templateVC onCreateTemplateView:dataArr view:scrollView];
//    scrollView.height = templateVC.tempViewHeight;
//    [self.controller addChildViewController:templateVC];
//
//    [self.contentView addSubview:scrollView];
//
//    [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
//
//        make.height.equalTo(@(scrollView.height));
//
//    }];
//}

/**
 配置数据 并适配UI
  */
-(void)paddingDataWithDataArray:(id)data
{
    [self clearContentView];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSArray *arr = data;
    if (arr == nil || arr.count == 0) {
        return;
    }
    NSDictionary *dic = arr[_indexPath.row];
    
    //带相片的控件
    if ([dic[@"widgetType"] isEqualToString:@"photo"] || [dic[@"widgetType"] isEqualToString:@"album"] ||[dic[@"widgetType"] isEqualToString:@"camera"] || [dic[@"widgetType"] isEqualToString:@"signature"]) {
        if (!_picView) {
            _picView = [[SEGTrackPhotoView alloc] initWithFrame:CGRectMake(0, 0, self.contentView.width, 63+12) data:dic];
            _picView.frame = CGRectMake(0, 0, self.contentView.width, 63+12);
            _picView.isDetailUIType = YES;
            _picView.parentVC = self.controller;
            _picView.backgroundColor = self.backgroundColor;
        }
        [self setupPhotoUI];
        
    }
    //录音控件
    else if ([dic[@"widgetType"] isEqualToString:@"record"]){
        
        /**
         注意:这里使用masony布局可能部分系统（ios10.0.1已知）可能会出现布局问题，cell复用时高度并没有设置成50 导致按钮点击时间失效   坑~！！
         
         chiang:已解决。该问题是由masonry和frame混用引起的，如果用masonry,就要统一地用masonry布局。
         */
        
        ControlTemplateViewRecordController *recordVC=[ControlTemplateViewRecordController sharedManagerRecord];
        recordVC.params=dic;
        [self.contentView addSubview:recordVC.view];
        
        // 移除分割线
        [recordVC.bgMainView.subviews.firstObject removeFromSuperview];
        
        // 修改字体大小
        UILabel *titleLabel = recordVC.bgMainView.subviews.firstObject;
        if ([titleLabel isKindOfClass:[UILabel class]]) {
            titleLabel.font = kFont_15;
            titleLabel.textColor = kColor_2;
        }
        
        CustomButtonView *button=(CustomButtonView*)recordVC.bgMainView.subviews[1];
        UILabel *titleLbl = [recordVC.bgMainView viewWithTag:111];
        button.userInteractionEnabled = YES;
        
        [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
            // iOS10 以上的适配
            if ([[[UIDevice currentDevice] systemVersion] floatValue] < 10.0) {
                make.left.right.top.equalTo(self);
                make.height.mas_equalTo(60);
            }else{
                make.edges.equalTo(self);
                make.height.mas_equalTo(60);
            }
            
        }];
        
        [recordVC.view mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.bottom.equalTo(self.contentView);
        }];
        [recordVC.bgMainView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.bottom.equalTo(self.contentView);
        }];
        [titleLbl mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(HEADSPACE);
            make.centerY.equalTo(recordVC.bgMainView.mas_centerY);
            make.width.mas_equalTo(70);
            make.height.equalTo(recordVC.bgMainView.mas_height);
        }];
        [button mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(100);
            make.centerY.equalTo(recordVC.bgMainView.mas_centerY);
            make.width.mas_equalTo(LYScreenWidth()-140);
            make.height.mas_equalTo(40);
        }];
        
    }
    //其他控件都以文本形式展示
    else{
        //一些特殊控件的文案显示需要格式化出来
        NSString *valueStr = [self getTextValueWith:dic];
        if ([dic[@"widgetType"] isEqualToString:@"statustext"]) { //- 状态控件需要特殊颜色
             [self.contentLabel extendAttributedString:valueStr lineSpace:LINESPACE_6 font:ORDER_DETAIL_CONTENT_FONT color:kColor_S2 lineBreakMode:NSLineBreakByTruncatingTail];
        }
        else{
             [self.contentLabel extendAttributedString:valueStr lineSpace:LINESPACE_6 font:ORDER_DETAIL_CONTENT_FONT color:kColor_1 lineBreakMode:NSLineBreakByTruncatingTail];
        }
        [self.titleLabel extendAttributedString:dic[@"title"] lineSpace:LINESPACE_6 font:ORDER_DETAIL_CONTENT_FONT color:kColor_2 lineBreakMode:NSLineBreakByTruncatingTail];
        [self setupCommonUI:arr];
    }
}


/**
 不同控件格式文案需要做适配
 */
-(NSString *)getTextValueWith:(NSDictionary *)dict
{
   __block NSString *valueStr = @"";
    NSString *widgetType = [SEGUtils ValueToString:dict[@"widgetType"]];
    id attrValue = dict[@"attrValue"];
    id initData = dict[@"initData"];
    //1.A类型数据 - initdata = [{"id": "urgency_id_1","isDefault": "0","value": "一般"},...]
    //            attrValue = string
    BOOL isValueType_A = [widgetType isEqualToString:@"radio"] || [widgetType isEqualToString:@"community_area"] || [widgetType isEqualToString:@"evaluate"] ;
    
    //2.B类型数据 - initdata = [{"id": "urgency_id_1","isDefault": "0","value": "一般"},...]
     //           attrValue = ["xxxxxx",...]
    BOOL isValueType_B = [widgetType isEqualToString:@"checkbox"] ;
    
    
    //3.C类型  initdata = {"url": "http:www.xxx.xx", "name":"协议名称","value": "0"}
    //         attrValue = string
    BOOL isValueType_C = [widgetType isEqualToString:@"protocol"];
    
    //4.D类型  initdata =    [{"id": "1","isDefault": "0","value": "员工1","userType":"2"},...]
    //         attrValue =  {"id": "1",value": "员工1","userType":"2"}
    BOOL isValueType_D = [widgetType isEqualToString:@"handler_radio"] || [widgetType isEqualToString:@"community_location"]
    || [widgetType isEqualToString:@"problem_class"] || [widgetType isEqualToString:@"radiohouse"];
   
    //5.E类型  initdata =    [{"id": "1","isDefault": "0","value": "员工1","userType":"2"},...]
    //         attrValue =  [{"id": "1", "value": "员工1","userType":"2"}]
    BOOL isValueType_E = [widgetType isEqualToString:@"handler_checkbox"];

    //6.F类型  initdata =   [{"id": "0","isDefault": "0","value": "异常","options": [{"id": "1","isDefault": "0","value": "卫生问题"}]}]
    //         attrValue = {"id":0,"option":["778","1"]}
    BOOL isValueType_F = [widgetType isEqualToString:@"radio_checkbox"];

    
    if (isValueType_A) {
        NSString *idKey = @"id";
        NSString *valueKey = @"value";
        if ([widgetType isEqualToString:@"community_area"]) {
            idKey = @"areaId";
            valueKey = @"areaName";
        }
        
        NSArray *data = [SEGUtils arrayWithJsonString:initData];
        if (data.count > 0) {
            [data enumerateObjectsUsingBlock:^(NSDictionary *radioDcit, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([[SEGUtils ValueToString:radioDcit[idKey]] isEqualToString:attrValue]) {
                    valueStr = radioDcit[valueKey];
                    *stop = YES;
                }
            }];
        }
    }
    
    else if (isValueType_B){
        NSArray *attrArray = [SEGUtils arrayWithJsonString:attrValue];
        NSArray *data = [SEGUtils arrayWithJsonString:initData];
        NSMutableArray *valueArr = [[NSMutableArray alloc] init];
        [attrArray enumerateObjectsUsingBlock:^(NSString *idStr, NSUInteger idx, BOOL * _Nonnull stop) {
            [data enumerateObjectsUsingBlock:^(NSDictionary *sourceDict, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([idStr isEqualToString:sourceDict[@"id"]]) {
                    [valueArr addObject:sourceDict[@"value"]];
                      *stop = YES;
                }
            }];
        }];
        valueStr =  [valueArr componentsJoinedByString:@"，"];
    }
    
    else if (isValueType_C){
        NSDictionary *initDataDict = [SEGUtils dictionaryWithJsonString:initData];
        NSString *textStr = [attrValue isEqualToString:@"1"]?@"同意":@"不同意";
        valueStr = [NSString stringWithFormat:@"%@《%@》",textStr,initDataDict[@"name"]];
    }
    
    else if (isValueType_D){
        NSDictionary *attrDict = [SEGUtils dictionaryWithJsonString:attrValue];
        valueStr = attrDict[@"value"];
    }
    
    else if (isValueType_E){
        NSArray *attrArray = [SEGUtils arrayWithJsonString:attrValue];
        NSMutableArray *valueArray = [[NSMutableArray alloc] init];
        [attrArray enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
            [valueArray addObject:dict[@"value"]];
        }];
        valueStr = [valueArray componentsJoinedByString:@"，"];
    }
    
    else if (isValueType_F){
        NSDictionary *attrDict = [SEGUtils dictionaryWithJsonString:attrValue];
        NSArray *initArray = [SEGUtils arrayWithJsonString:initData];
        valueStr = [self getRadio_CheckboxValueWith:initArray attrValue:attrDict];
    }
    //其他类型直接将attrValue显示
    else{
        valueStr = [SEGUtils ValueToString:attrValue];
    }
    
    //处理换行符
    valueStr = [valueStr stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"];
    return valueStr;
    
}

/**
 获取单复选控件的展示的值
  */
-(NSString *)getRadio_CheckboxValueWith:(id)initData attrValue:(id)attrValue
{
    NSDictionary *attrDict = attrValue;
    NSString *idStr = [SEGUtils ValueToString:attrDict[@"id"]];
    NSArray *initDataArray  = initData;
    //反查
    __block NSMutableArray *valueArr = [[NSMutableArray alloc] init];
    if (initDataArray.count > 0) {
        [initDataArray enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
            if ( [[SEGUtils ValueToString:dict[@"id"]] isEqualToString:idStr]) {
                NSArray *options = dict[@"options"];
                if (options.count > 0) {
                    [options enumerateObjectsUsingBlock:^(NSDictionary *optionDict, NSUInteger idx, BOOL * _Nonnull stop) {
                        
                        if ([attrDict[@"option"] containsObject:[SEGUtils ValueToString:optionDict[@"id"]]]) {
                            [valueArr addObject:optionDict[@"value"]];
                        }
                    }];
                }
                else{
                    [valueArr addObject:dict[@"value"]];
                }
            }
        }];
    }
    
    NSString *valueStr = [valueArr componentsJoinedByString:@"，"];
    return valueStr;
    
}

-(void)onFeeRefeshUI
{
    
}

- (void)setupCommonUI:(NSArray*)arr
{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    [self.contentView addSubview:self.titleLabel];
    [self.contentView addSubview:self.contentLabel];
    [self.contentView addSubview:self.foldButton];
    
    // 计算contentLabel需要显示的行数
    CGFloat contentWidth = floor(LYScreenWidth() - 100 - 15);
    CGSize contentSize = [self.contentLabel textRectForBounds:CGRectMake(0, 0, contentWidth, LYScreenHeight()) limitedToNumberOfLines:0].size;
    CGSize titleSize = [self.titleLabel textRectForBounds:CGRectMake(0, 0, TITLE_WIDTH, LYScreenHeight()) limitedToNumberOfLines:0].size;
    CGFloat foldButtonHeight = 30;
    CGFloat foldButtonTop = 8;
    
    CGFloat lineNumber = floor((contentSize.height + LINESPACE_6) / (ORDER_DETAIL_CONTENT_FONT.lineHeight + LINESPACE_6));
    CGFloat contentHeight = contentSize.height;
    CGFloat dispalyTotalHeight = 0;
    
    self.foldButton.hidden = YES;
    self.foldButton.selected = self.foldStatus;
    if (lineNumber > 4) {
        self.foldButton.hidden = NO;
        // self.foldStatus yes展开 no折叠
        if (self.foldStatus) {
            self.contentLabel.numberOfLines = 0;
        } else {
            self.contentLabel.numberOfLines = 4;
            contentHeight = (ORDER_DETAIL_CONTENT_FONT.lineHeight + LINESPACE_6) * 4 - LINESPACE_6;
        }
        dispalyTotalHeight = MAX(titleSize.height, contentHeight + foldButtonHeight);
    } else {
        dispalyTotalHeight = MAX(titleSize.height, contentSize.height);
    }
    
    CGFloat bottomMargin = 20;
    CGFloat topMargin = 15;
    
    if (arr.count <= 1) {
        // 详细数组个数等于1
        topMargin = 15;
        bottomMargin = 30;
    } else {
        // 详细数组个数大于1
        if (self.indexPath.row == 0) {
            // 第一条
            topMargin = 15;
            bottomMargin = 20;
        } else if (self.indexPath.row == arr.count-1) {
            // 最后一条
            topMargin = 6;
            bottomMargin = 20;
        } else {
            // 中间条
            topMargin = 7.5;
            bottomMargin = 15;
        }
    }
    dispalyTotalHeight = dispalyTotalHeight + topMargin + bottomMargin;
    
    [self.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(topMargin);
        make.width.mas_equalTo(TITLE_WIDTH);
    }];
    
    [self.contentLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(100);
        make.top.mas_equalTo(topMargin);
        make.width.mas_equalTo(contentWidth);
        make.height.mas_equalTo(ceil(contentHeight));
    }];
    
    [self.foldButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentLabel);
        make.top.equalTo(self.contentLabel.mas_bottom).offset(foldButtonTop);
        make.size.mas_equalTo(CGSizeMake(60, foldButtonHeight));
    }];
    
    [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
        make.height.mas_equalTo(dispalyTotalHeight);
    }];
}


- (void)setupCommonUI
{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [self.contentView addSubview:self.titleLabel];
    [self.contentView addSubview:self.contentLabel];
    [self.contentView addSubview:self.arrow];
    
    [_titleLabel mas_remakeConstraints:^(MASConstraintMaker* make) {
        make.left.equalTo(self.contentView).offset(15);
        make.centerY.equalTo(self.contentView.mas_centerY);
    }];
    
    [_contentLabel mas_remakeConstraints:^(MASConstraintMaker* make) {
        make.left.equalTo(self.contentView).offset(100);
        make.centerY.equalTo(self.contentView.mas_centerY);
    }];
    
    [_arrow mas_remakeConstraints:^(MASConstraintMaker* make) {
        make.right.equalTo(self.contentView).offset(-20);
        make.centerY.equalTo(self.contentView.mas_centerY);
    }];
    [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        // iOS10 以上的适配
        if ([[[UIDevice currentDevice] systemVersion] floatValue] < 10.0) {
            make.left.right.top.equalTo(self);
            make.bottom.equalTo(self.contentLabel.mas_bottom).offset(15);
        }else{
            make.edges.equalTo(self);
            make.bottom.equalTo(self.contentLabel.mas_bottom).offset(15);
        }
    }];
    
}


- (void)setupPhotoUI
{
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
//    [self.contentView addSubview:self.titleLabel];
    [self.contentView addSubview:self.picView];
    
//    CGSize size1=STRING_SIZE_FONT(60, self.titleLabel.text, kFont_14);
//
//    [_titleLabel mas_remakeConstraints:^(MASConstraintMaker* make) {
//        make.left.equalTo(self.contentView).offset(15);
//        make.size.mas_equalTo(CGSizeMake(60, size1.height));
//        make.centerY.equalTo(self.contentView);
//
//    }];
    
    [self.picView mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.contentView).offset(0);
        make.left.equalTo(self.contentView).offset(15);
         make.size.mas_equalTo(CGSizeMake(LYScreenWidth(), 63+12));
    }];
    
    [self.contentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        // iOS10 以上的适配
        if ([[[UIDevice currentDevice] systemVersion] floatValue] < 10.0) {
            make.left.right.top.equalTo(self);
            make.bottom.equalTo(self.picView.mas_bottom).offset(15);
        }else{
            make.edges.equalTo(self);
            make.bottom.equalTo(self.picView.mas_bottom).offset(15);
        }
    }];
    
    NSLog(@"pic = %@",NSStringFromCGRect(self.picView.frame));
}


/**
 展开按钮事件
 */

- (IBAction)openAction:(UIButton *)sender {
    
}

- (void)foldButtonDidTap:(UIButton *)sender {
    sender.selected = !sender.selected;
    self.foldButtonTapBlock(sender.isSelected);
}


#pragma mark - Getter & Setter

-(UILabel*)titleLabel
{
    if (_titleLabel==nil) {
        _titleLabel=[[UILabel alloc] init];
        _titleLabel.textColor=kColor_2;
        _titleLabel.font=kFont_15;
        _titleLabel.numberOfLines=0;
    }
    return _titleLabel;
}

-(UILabel*)contentLabel
{
    if (_contentLabel==nil) {
        _contentLabel=[[UILabel alloc] init];
        _contentLabel.textColor=kColor_1;
        _contentLabel.font=kFont_15;
        _contentLabel.numberOfLines = 0;
    }
    return _contentLabel;
}

-(UIImageView*)arrow
{
    if (_arrow==nil) {
        UIImage* image = [UIImage imageWithContentsOfFile:SEGPicName(@"btn_more_gray")];
        _arrow = [[UIImageView alloc] init];
        [_arrow setImage:image];
    }
    return _arrow;
}
- (SEGTrackPhotoView*)picView
{
    
    return _picView;
}

-(NSIndexPath*)indexPath
{
    if (_indexPath==nil) {
        _indexPath=[[NSIndexPath alloc] init];
    }
    return _indexPath;
}

- (UIButton *)foldButton {
    if (!_foldButton) {
        _foldButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setTitle:@"全文" forState:UIControlStateNormal];
            [button setTitle:@"收起" forState:UIControlStateSelected];
            [button setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_zhankai")] forState:UIControlStateNormal];
            [button setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_shouqi")] forState:UIControlStateSelected];
            [button setTitleColor:kColor_S3 forState:UIControlStateNormal];
            button.titleLabel.font = kFont_14;
            [button addTarget:self action:@selector(foldButtonDidTap:) forControlEvents:UIControlEventTouchUpInside];
            button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            button.imageEdgeInsets = UIEdgeInsetsMake(0, 35, 0, 0);
            button.titleEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
            button;
        });
    }
    return _foldButton;
}


@end
